package com.ruoyi.common.filter;

import com.ruoyi.common.utils.StringUtils;
import org.springframework.http.MediaType;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * TODO ??没看出哪里实现防止 重复提交 Repeatable 过滤器
 * 
 * @author ruoyi
 */
public class RepeatableFilter implements Filter
{
    @Override
    public void init(FilterConfig filterConfig) throws ServletException
    {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException
    {
        ServletRequest requestWrapper = null;
        if (request instanceof HttpServletRequest
                //判断前端request请求的Content类型是不是application/json,因为post表单提交使用的是application/json
                && StringUtils.equalsAnyIgnoreCase(request.getContentType(), MediaType.APPLICATION_JSON_VALUE))
        {
            //将requestWrapper转换为重写后的RepeatedlyRequestWrapper对象,该对象是在RepeatedlyRequestWrapper中定义的,可以创建一个可以重复读取inputStream的request
            requestWrapper = new RepeatedlyRequestWrapper((HttpServletRequest) request, response);
        }
        if (null == requestWrapper)
        {
            /**如果还有别的过滤器，那么将处理好的请求传给下个过滤器，依此类推，当所有的过滤器都把这个请求处理好了之后，再将处理完的请求发给servlet；如果就这一个过滤器，那么就将处理好的请求直接发给servlet。*/
            chain.doFilter(request, response);
        }
        else
        {
            chain.doFilter(requestWrapper, response);
        }
    }

    @Override
    public void destroy()
    {

    }
}
